package com.yipao.admin.web;

import com.yipao.core.config.MobileProperties;
import com.yipao.core.constant.GlobalConstant;
import com.yipao.core.mqtt.service.MqttSendService;
import com.yipao.core.mqtt.vo.MqttSendAdVo;
import com.yipao.core.mqtt.vo.MqttSendVo;
import com.yipao.core.storage.StorageService;
import com.yipao.db.domain.YipaoStorage;
import com.yipao.db.domain.devinfo.DevInfo;
import com.yipao.db.service.devinfo.DevInfoService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.yipao.admin.annotation.RequiresPermissionsDesc;
import com.yipao.core.util.ResponseUtil;
import com.yipao.core.validator.Order;
import com.yipao.core.validator.Sort;
import com.yipao.db.domain.YipaoAd;
import com.yipao.db.service.YipaoAdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;

/**
 * 广告管理
 *
 * @author tianhao
 */
@RestController
@RequestMapping("/admin/ad")
@Validated
public class AdminAdController {
    private final Log logger = LogFactory.getLog(AdminAdController.class);

    @Resource
    private YipaoAdService adService;
    @Resource
    private StorageService storageService;

    @Resource
    private MqttSendService mqttSendService;

    @Resource
    private MobileProperties mobileProperties;

    @Resource
    private DevInfoService devInfoService;

    @RequiresPermissions("admin:ad:list")
    @RequiresPermissionsDesc(menu = {"推广管理", "广告管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String name, String content,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<YipaoAd> adList = adService.querySelective(name, content, page, limit, sort, order);
        return ResponseUtil.okList(adList);
    }

    private Object validate(YipaoAd ad) {
        String name = ad.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }
        String content = ad.getContent();
        if (StringUtils.isEmpty(content)) {
            return ResponseUtil.badArgument();
        }
        return null;
    }

    @RequiresPermissions("admin:ad:create")
    @RequiresPermissionsDesc(menu = {"推广管理", "广告管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody YipaoAd ad) {
        Object error = validate(ad);
        if (error != null) {
            return error;
        }
        adService.add(ad);
        return ResponseUtil.ok(ad);
    }

    @RequiresPermissions("admin:ad:upload")
    @RequiresPermissionsDesc(menu = {"推广管理", "广告管理"}, button = "添加(拖拽)")
    @PostMapping("/upload")

    public Object upload(@RequestParam("file") MultipartFile file) {
        try {
            YipaoStorage store = storageService.store(file.getInputStream(), file.getSize(),
                    file.getContentType(), file.getOriginalFilename());
            YipaoAd ad = new YipaoAd();
            ad.setName(store.getName().substring(0, store.getName().indexOf(".")));
            ad.setContent(ad.getName());
            ad.setPosition((byte) 1);
            ad.setDeleted(GlobalConstant.DeleteStatus.N);
            ad.setEnabled(GlobalConstant.ENABLED_STATUS_Y);
            ad.setUrl(store.getUrl());
            adService.add(ad);
            ad.getId();



            List<String> iMeis = devInfoService.queryAllDev();
            for (String iMei : iMeis) {
                    //参数1 : ad的Id,  参数2 每个设备的Imei, 参数3 cmd  参数4 上传全局常量定义(10) ,参数 5 文件类型
                mqttSendService.send(mobileProperties.getMqttUrl(),new MqttSendVo(ad.getId()+"",iMei,1,GlobalConstant.AndroidAdOt.AD_UPLOAD,file.getContentType()));
            }
            return ResponseUtil.ok(ad);
        } catch (IOException e) {
            logger.error("upload", e);
            return ResponseUtil.fail();
        }
    }

    @RequiresPermissions("admin:ad:read")
    @RequiresPermissionsDesc(menu = {"推广管理", "广告管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        YipaoAd ad = adService.findById(id);
        return ResponseUtil.ok(ad);
    }

    @RequiresPermissions("admin:ad:update")
    @RequiresPermissionsDesc(menu = {"推广管理", "广告管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody YipaoAd ad) {
        Object error = validate(ad);
        if (error != null) {
            return error;
        }
        if (adService.updateById(ad) == 0) {

            return ResponseUtil.updatedDataFailed();

        }
        return ResponseUtil.ok(ad);
    }

    @RequiresPermissions("admin:ad:delete")
    @RequiresPermissionsDesc(menu = {"推广管理", "广告管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody YipaoAd ad) {
        Integer id = ad.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        List<String> iMeis = devInfoService.queryAllDev();
        for (String iMei : iMeis) {
            //参数1 : ad的Id,  参数2 每个设备的Imei, 参数3 cmd  参数4 上传全局常量定义(10) ,参数 5 广告ad
            mqttSendService.send(mobileProperties.getMqttUrl(),new MqttSendVo(ad.getId()+"",iMei,1,GlobalConstant.AndroidAdOt.AD_UPLOAD,ad));
        }
        adService.deleteById(id);
        return ResponseUtil.ok();
    }

}
